package com.cp.admin.api.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cp.admin.api.entity.CodeEnum;
import com.cp.admin.api.entity.Result;
import com.cp.admin.api.entity.vo.AlbumVO;
import com.cp.admin.api.utils.PKGeneratorUtils;
import com.cp.admin.api.utils.RedisUtils;
import com.cp.admin.modular.user.model.UserBasics;
import com.cp.admin.modular.user.model.UserPhoto;
import com.cp.admin.modular.user.model.UserPhotoAlbum;
import com.cp.admin.modular.user.service.*;
import com.cp.admin.socket.MyWebSocket;
import com.cp.core.support.StrKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/photo")
@Api(value = "照片操作", tags = "照片操作")
public class PhotoController extends BaseController{
    @Autowired
    private IUserBasicsService userService;
    @Autowired
    private IUserPhotoService userPhotoService;
    @Autowired
    private IUserPhotoAlbumService userPhotoAlbumService;
    @Autowired
    private MyWebSocket webSocket;
    @Autowired
    private UpImgService upImgService;


    @ApiOperation("创建相册")
    @RequestMapping(value = "/createAlbum", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "authority", value = "权限 0仅对好友开放 1公开 -1仅自己可见", dataType = "String", required = true, paramType = "query")
    })
    public Result createAlbum(Long userId, Integer authority) {
        if (userId == null || authority == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserPhotoAlbum album = new UserPhotoAlbum();
        album.setId(PKGeneratorUtils.getInstance().nextId());
        album.setAuthority(authority);
        album.setUserId(userId);
        album.setCreateTime(new Date());
        if (userPhotoAlbumService.insert(album)) {
            return new Result(album);
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("上传照片")
    @RequestMapping(value = "/uploadPhotos", method = RequestMethod.POST)
    @ApiImplicitParams({
            // @ApiImplicitParam(name = "photoUrl", value = "照片", dataType = "file", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "albumId", value = "所属相册ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "payPhoto", value = "是否付费照片0不是1是", dataType = "Integer", required = true, paramType = "query"),
            @ApiImplicitParam(name = "amount", value = "付费金额", dataType = "String", required = true, paramType = "query")
    })
    public Result uploadPhotos(MultipartFile photoUrl, Long userId, Long albumId, Integer payPhoto, BigDecimal amount) {
        if (photoUrl == null || userId == null || payPhoto == null || amount==null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserPhotoAlbum upa = userPhotoAlbumService.selectById(albumId);
        if (upa == null) {
            return new Result(CodeEnum.FAIL_10005);
        }
        UserPhoto photo = new UserPhoto();
        Long photoId = PKGeneratorUtils.getInstance().nextId();
        photo.setId(photoId);
        photo.setUserId(userId);
        try {
            String pU=upImgService.updateHead(photoUrl,CodeEnum.FILEDIR_11.getMsg());
            photo.setPhotoUrl(pU);
        }catch (Exception e){
        }
        photo.setPayPhoto(payPhoto);
        photo.setIncome(new BigDecimal(0.00));
        if (payPhoto == 1) {
            if (amount.compareTo(new BigDecimal(0))==-1){
                return new Result(CodeEnum.FAIL_10008);
            }
            photo.setAmount(amount);
        } else {
            photo.setAmount(new BigDecimal(0.00));
        }
        photo.setAlbumId(albumId);
        photo.setStatus(0);
        photo.setCreateTime(new Date());
        upa.setUpdateTime(new Date());
        if (userPhotoService.insert(photo) && userPhotoAlbumService.updateById(upa)) {
            return new Result(photo);
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("查看相册")
    @RequestMapping(value = "/viewAlbums", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "albumId", value = "相册Id", dataType = "String", required = true, paramType = "query")
    })
    public Result viewAlbums(Long userId, Long albumId) {
        if (userId == null || albumId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserPhotoAlbum result = userPhotoAlbumService.selectById(albumId);
        List<AlbumVO> list = new ArrayList();
        List<UserPhotoAlbum> result1 = userPhotoAlbumService.selectList(new EntityWrapper().eq("user_id", userId));
        for (UserPhotoAlbum album : result1) {
            List<UserPhoto> result2 = userPhotoService.selectList(new EntityWrapper().eq("album_id", album.getId()).eq("status", 0));
            for (UserPhoto photos : result2) {
                AlbumVO albumVO = new AlbumVO();
                albumVO.setUserId(album.getUserId());
                albumVO.setAlbumId(album.getId());
                albumVO.setAuthority(album.getAuthority());
                albumVO.setAmount(photos.getAmount());
                albumVO.setPayPhoto(photos.getPayPhoto());
                albumVO.setPhotoUrl(photos.getPhotoUrl());
                albumVO.setStatus(photos.getStatus());
                if (result.getUserId() == userId) {//查看自己的相册
                    albumVO.setIncome(photos.getIncome());//只有自己能看自己的照片收益
                    list.add(albumVO);
                }
                if (album.getAuthority() != 1) {//查看他人非公开相册
                    return new Result(CodeEnum.FAIL_10014);
                } else {//查看他人公开相册，相册内照片分为收费和不收费
                    if (albumVO.getPayPhoto() == 1) {
                        albumVO.setPhotoUrl("该照片收费!");
                    }
                    list.add(albumVO);
                }
            }
        }
        return new Result(list);
    }

    @ApiOperation("查看收费照片")
    @RequestMapping(value = "/viewPhoto", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "照片ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "查看人ID", dataType = "String", required = true, paramType = "query")
    })
    public Result viewPhoto(Long id, Long userId) {
        if (id == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserPhoto photo = userPhotoService.selectById(id);
        if (photo == null || photo.getStatus() == 1) {
            return new Result(CodeEnum.FAIL_10006);
        }
        if (photo.getPayPhoto() == 0) {
            return new Result(CodeEnum.FAIL_10015);
        }
        if (photo.getUserId().equals(userId)) {
            return new Result(photo.getPhotoUrl());
        }
        UserBasics user1 = userService.selectById(userId);
        UserBasics user2 = userService.selectById(photo.getUserId());
        if (user1.getPeasQuantity().compareTo(photo.getAmount()) == -1) {
            return new Result(CodeEnum.FAIL_10016);
        }
        user1.setPeasQuantity(user1.getPeasQuantity().subtract(photo.getAmount()));
        user2.setPeasQuantity(user2.getPeasQuantity().add(photo.getAmount()));
        photo.setIncome(photo.getIncome().add(photo.getAmount()));
        if (userService.updateById(user1) &&
                userService.updateById(user2) &&
                userPhotoService.updateById(photo)) {
            return new Result(photo.getPhotoUrl());
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("删除照片")
    @RequestMapping(value = "/deletePhoto", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "照片ID", dataType = "String", required = true, paramType = "query")
    })
    public Result deletePhoto(Long id) {
        if (id == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserPhoto album = userPhotoService.selectById(id);
        if (album == null) {
            return new Result(CodeEnum.FAIL_10006);
        }
        album.setStatus(1);
        album.setUpdateTime(new Date());
        userPhotoService.updateById(album);
        return new Result(album);
    }
}
